package redisgw

import (
	"context"
	"fmt"
	"fronter/config"
	"time"

	"github.com/go-redis/redis/v8"
	"github.com/sirupsen/logrus"
)

var p_redis_client *redis.Client
var myerr error
var emptyMap map[string]string

func init() {
	redis_instances := config.Get().Redis
	for _, instance := range redis_instances {
		logrus.Infoln("try connect redis instance:", instance)
		p_redis_client = redis.NewClient(&redis.Options{
			Addr:     instance,
			Password: "lzcredis", // no password set
			DB:       0,  // use default DB
		})
	}
}

func Lpush(key string, val string) error {
	var ctx = context.Background()
	p_redis_client.LPush(ctx, key, val)
	return nil
}

func Expire(key string, second int64) error {
	var ctx = context.Background()
	p_redis_client.Expire(ctx, key, time.Second*time.Duration(second))
	return nil
}

func HDel(key string, fields ...string) {
	logrus.Infoln("hdel key:", key, ", member", fields)
	var ctx = context.Background()
	p_redis_client.HDel(ctx, key, fields...)
}

func HGetall(key string) map[string]string {
	var ctx = context.Background()
	resMap, err := p_redis_client.HGetAll(ctx, key).Result()
	if err != nil {
		return emptyMap
	}
	return resMap
}

func HSet(key string, values ...interface{}) error {
	var ctx = context.Background()
	p_redis_client.HSet(ctx, key, values)
	return nil
}

func IncrBy(key string, num int64) string {
	var ctx = context.Background()
	val, err := p_redis_client.IncrBy(ctx, key, num).Result()
	if err != nil {
		logrus.Errorln("incyby failed! error:", err)
		return ""
	}
	return fmt.Sprintf("%d", val)
}

func Set(key string, val string) {
	var ctx = context.Background()
	err := p_redis_client.Set(ctx, key, val, 0).Err()
	if err != nil {
		logrus.Errorln("set key:", key, " failed！ redis err:", err)
	}
}

func HGet(key string, field string) *string {
	var ctx = context.Background()
	val, err := p_redis_client.HGet(ctx, key, field).Result()
	if err != nil {
		logrus.Errorln("hget key:", key+"-"+field, " failed！ redis err:", err)
		return nil
	}
	return &val
}

func Get(key string) *string {
	var ctx = context.Background()
	val, err := p_redis_client.Get(ctx, key).Result()
	if err != nil {
		logrus.Errorln("get key:", key, " failed！ redis err:", err)
		return nil
	}
	if err == redis.Nil {
		logrus.Infoln(key, " does not exist")
		return nil
	}
	return &val
}
